package com.hundsun.documentripper.utils;

import com.github.difflib.text.DiffRow;
import com.hundsun.documentripper.domain.other.word.StyleInfo;
import com.hundsun.documentripper.domain.other.word.WordBuildInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * html转word
 *
 * @author lonely_man
 * @since 2021年2月1日
 */
public class HtmlToWordUtil {

    /**
     * word格式html默认头部
     */
    private final static String wordHtmlHead = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n" +
            "xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"\n" +
            "xmlns=\"http://www.w3.org/TR/REC-html40\"><head>\n" +
            "    <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->\n" +
            "</head><body>";

    private final static String wordHtmlFoot = "</body></html>";

    /**
     * 构建html内容
     */
    public static String buildHtml(List<WordBuildInfo> infoList) {
        if (StringUtil.isEmpty(infoList)) {
            return "";
        }

        StringBuilder htmlContent = new StringBuilder(wordHtmlHead);
        for (WordBuildInfo info : infoList) {
            if (StringUtil.isNotBlank(info.getTitle())) {
                htmlContent.append("<p ");
                getStyleContent(htmlContent, info.getTitleStyle());
                htmlContent.append(">").append(info.getTitle()).append("</p>");
            }
            if (StringUtil.isNotBlank(info.getContent())) {
                htmlContent.append("<p ");
                getStyleContent(htmlContent, info.getContentStyle());
                htmlContent.append(">").append(info.getContent()).append("</p>");
            }
        }
        htmlContent.append(wordHtmlFoot);
        return htmlContent.toString();
    }

    /**
     * 获取标签的样式代码
     */
    private static void getStyleContent(StringBuilder sb, List<StyleInfo> styleInfos) {
        sb.append("style=\"");
        for (StyleInfo styleInfo : styleInfos) {
            sb.append(styleInfo.getStyleKey()).append(":").append(styleInfo.getStyleValue()).append(";");
        }
        sb.append("\"");
    }

    /**
     * 生成文件比对结果word
     */
    public static String createComparisonWord(List<DiffRow> deltas) {
        int insertNum = 0, changeNum = 0, deleteNum = 0, equalNum = 0;
        List<String> insertStr = new ArrayList<>();
        List<String> changeStr = new ArrayList<>();
        List<String> deleteStr = new ArrayList<>();
        List<String> equalStr = new ArrayList<>();
        for (DiffRow row : deltas) {
            DiffRow.Tag tag = row.getTag();
            if (tag == DiffRow.Tag.INSERT) {
                insertNum++;
                if (StringUtil.isNotBlank(row.getNewLine())) {
                    insertStr.add("新增内容：[" + row.getNewLine() + "]");
                }
            } else if (tag == DiffRow.Tag.CHANGE) {
                changeNum++;
                changeStr.add("修改内容：由[" + row.getOldLine() + "]修改为[" + row.getNewLine() + "]");
            } else if (tag == DiffRow.Tag.DELETE) {
                deleteNum++;
                if (StringUtil.isNotBlank(row.getOldLine())) {
                    deleteStr.add("删除内容：[" + row.getOldLine() + "]");
                }
            } else if (tag == DiffRow.Tag.EQUAL) {
                equalNum++;
                if (StringUtil.isNotBlank(row.getOldLine())) {
                    equalStr.add("未修改内容：[" + row.getOldLine() + "]");
                }
            } else {
                throw new IllegalStateException("Unknown pattern tag: " + tag);
            }
        }
        String title = "<p style=\"text-align: center;font-size: 3rem;color: #191919;font-weight: 600;font-family: 仿宋;\">文档对比结果</p>";
        String countStr = "<p style=\"font-size: 2rem;color: red;font-family: 黑体;\">本次对比出新增" + insertNum + "项，" +
                "修改" + changeNum + "项，删除" + deleteNum + "项，未修改" + equalNum + "项。</p>";
        StringBuilder insertCountStr = new StringBuilder();
        if (insertNum > 0) {
            insertCountStr = new StringBuilder("<p style=\"font-size: 1rem;color: black;font-family: 黑体;\">新增内容详情如下：</p>");
            for (String str : insertStr) {
                insertCountStr.append("<p style=\"font-size: 1rem;color: gray;\">").append(str).append("</p>");
            }
        }
        StringBuilder changeCountStr = new StringBuilder();
        if (changeNum > 0) {
            changeCountStr = new StringBuilder("<p style=\"font-size: 1rem;color: black;font-family: 黑体;\">修改内容详情如下：</p>");
            for (String str : changeStr) {
                changeCountStr.append("<p style=\"font-size: 1rem;color: gray;\">").append(str).append("</p>");
            }
        }
        StringBuilder deleteCountStr = new StringBuilder();
        if (deleteNum > 0) {
            deleteCountStr = new StringBuilder("<p style=\"font-size: 1rem;color: black;font-family: 黑体;\">删除内容详情如下：</p>");
            for (String str : deleteStr) {
                deleteCountStr.append("<p style=\"font-size: 1rem;color: gray;\">").append(str).append("</p>");
            }
        }
        StringBuilder equalCountStr = new StringBuilder();
        if (equalNum > 0) {
            equalCountStr = new StringBuilder("<p style=\"font-size: 1rem;color: black;font-family: 黑体;\">未修改内容详情如下：</p>");
            for (String str : equalStr) {
                equalCountStr.append("<p style=\"font-size: 1rem;color: gray;\">").append(str).append("</p>");
            }
        }
        return wordHtmlHead + title + countStr + insertCountStr + changeCountStr + deleteCountStr + equalCountStr + wordHtmlFoot;
    }
}
